/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.menosehmais.framework.converter;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.ioc.ApplicationScoped;
import java.util.ResourceBundle;
import org.joda.time.LocalDate;

/**
 * ISO8601 format (yyyy-MM-dd).
 * @author Quintino
 */
@Convert(LocalDate.class)
@ApplicationScoped
public class LocalDateConverter implements Converter<LocalDate> {

    @Override
    public LocalDate convert(String value, Class<? extends LocalDate> type, ResourceBundle bundle) {
        return fromString(value);
    }

    public static LocalDate fromString(String value) {
        LocalDate date = null;
        int year = 0, month = 0, day = 0;

        try {
            if (value != null) {
                value =  value.trim();
                if(!value.isEmpty() && value.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
                    String fields[] = value.split("-");
                    year = Integer.parseInt(fields[0]);
                    month = Integer.parseInt(fields[1]);
                    day = Integer.parseInt(fields[2]);

                    date = new LocalDate(year, month, day);

                    return date;
                } else if(!value.isEmpty()) {
                    throw new ConversionError( "LocalDate: " + value + ", é inválido." );
                }
            }

            return null;
        } catch (Exception e) {
            throw new ConversionError( "LocalDate: " + value + ", é inválido. " + e.getMessage() );
        }
    }

    public static String asString(LocalDate date){
        if(date == null) {
            return null;
        }
        return date.toString("yyyy-MM-dd");
    }
}
